package com.example.quiz.controller.admin;

import com.example.quiz.common.Result;
import com.example.quiz.model.Category;
import com.example.quiz.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/admin/category")
public class CategoryManageController {

    @Autowired
    private CategoryService categoryService;

    @GetMapping("/manage")
    public String managePage() {
        return "admin/category/manage";
    }

    @GetMapping("/api/list")
    @ResponseBody
    public Result<List<Category>> getCategories() {
        return Result.success(categoryService.getAll());
    }

    @PostMapping("/api/add")
    @ResponseBody
    public Result<Integer> addCategory(@RequestBody Category category) {
        int result = categoryService.add(category);
        if (result > 0) {
            return Result.success(result);
        }
        return Result.error("添加失败");
    }

    @PutMapping("/api/update")
    @ResponseBody
    public Result<Integer> updateCategory(@RequestBody Category category) {
        int result = categoryService.update(category);
        if (result > 0) {
            return Result.success(result);
        }
        return Result.error("更新失败");
    }

    @DeleteMapping("/api/delete/{id}")
    @ResponseBody
    public Result<Integer> deleteCategory(@PathVariable Long id) {
        int result = categoryService.deleteById(id);
        if (result > 0) {
            return Result.success(result);
        }
        return Result.error("删除失败");
    }
}